
# 购物车数据合并
import base64
import pickle

from django_redis import get_redis_connection


def merge_cookie_redis_data(request, response):
    """

    :param request: 获取cookie数据跟redis数据
    :param response: 清除cookie数据的
    :return:
    """
    cookie_cart = request.COOKIES.get('carts')

    cookie_cart_dict = {}
    if cookie_cart:
        cookie_cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
    else:
        return response

    # 数据合并
    redis_conn = get_redis_connection('carts')
    for sku_id, selected_count in cookie_cart_dict.items():
        redis_conn.hset('carts_%s' % request.user.id, sku_id, selected_count['count'])
        selected = selected_count['selected']
        if selected:
            redis_conn.sadd(' selected_%s' % request.user.id, sku_id)
        else:
            redis_conn.srem('selected_%s' % request.user.id, sku_id)

    response.delete_cookie('carts')
    response.set_cookie('username', request.user.username)
    return response